'use client';

import {useEffect, useState} from 'react';
import {SubmitHandler, useForm, useWatch} from 'react-hook-form';
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import Button from "@/components/ui/Button/Button";
import {getFerryData, saveFerry, updateFerry} from "@/lib/data";
import {TypeCaptain, TypeFerry} from "@/shared/types";
import {useRouter, useSearchParams} from "next/navigation";
import styles from "./ShipAddPage.module.css";
import {ceil} from "lodash";
import FormSelect from "@/components/ui/Forms/FormElements/FormSelect";
import Image from "next/image";
import CapFerrySkeleton from "@/components/Skeletons/CapFerrySkeleton";
import {getObj} from "@/services/api_service";

export default function FerryForm() {
    const {
        register,
        handleSubmit,
        formState: {errors},
        setValue,
        control,
    } = useForm<TypeFerry>();
    const {push} = useRouter()

    const [currentImageUrl, setCurrentImageUrl] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [captainOptions, setCaptainOptions] = useState([{value: '', label: ''}]);
    const [isVehicleType, setIsVehicleType] = useState(false);

    const size = useWatch({control, name: 'size', defaultValue: 0});
    useEffect(() => {
        setValue('vehicle_capacity', ceil(Number(size) / (2.55 * 6)));
    }, [size, setValue]);

    const ferryType = useWatch({control, name: 'ferry_type', defaultValue: ''});
    useEffect(() => {
        ferryType === 'Автомобильный' ? setIsVehicleType(true) : setIsVehicleType(false);
    }, [ferryType, setValue]);

    const searchParams = useSearchParams();
    const ferryId = searchParams.get('id');

    useEffect(() => {
            const loadFerryData = async () => {
                if (ferryId) {
                    const ferry = await getFerryData(ferryId);
                    setValue('name', ferry.name);
                    ferry.captain && setValue('captain_id', ferry.captain.id);
                    setValue('ferry_type', ferry.ferry_type);
                    ferry.size && setValue('size', ferry.size);
                    ferry.vehicle_capacity && setValue('vehicle_capacity', ferry.vehicle_capacity);
                    setValue('passenger_capacity', ferry.passenger_capacity);
                    if (ferry.image) {
                        setCurrentImageUrl(ferry.image);
                    }
                }
                setIsLoading(false);
            };

            const getCaptainsData = async () => {
                const captains: TypeCaptain[] = await getObj('/api/ships/captains/details/');
                const captainOptions = captains.map(captain => {
                    return {
                        value: captain.id.toString(),
                        label: `${captain.last_name} ${captain.first_name} ${captain.patronymic}`
                    };
                });
                setCaptainOptions(captainOptions)
            }

            getCaptainsData().catch(err => console.error('Ошибка загрузки данных капитанов:', err));
            loadFerryData().catch(err => console.error('Ошибка загрузки данных парома:', err));
        }, [ferryId, setValue]
    );

    const onSubmit: SubmitHandler<TypeFerry> = async (data) => {
        const formData = new FormData();
        formData.append('name', data.name);
        formData.append('captain_id', data.captain_id);
        formData.append('ferry_type', data.ferry_type);
        data.size && formData.append('size', data.size.toString());
        data.vehicle_capacity && formData.append('vehicle_capacity', data.vehicle_capacity.toString());
        formData.append('passenger_capacity', data.passenger_capacity.toString());

        if (data.image && data.image.length > 0) {
            formData.append('image', data.image[0]);
        }
        console.log(Object.fromEntries(formData.entries()))

        try {
            if (ferryId) {
                await updateFerry(formData, ferryId);
            } else {
                await saveFerry(formData);
            }
            push('/admin/ships/');
        } catch (error) {
            console.error('Ошибка при сохранении парома:', error);
        }
    };

    const ferryTypeOptions = [
        {value: 'Пассажирский', label: 'Пассажирский'},
        {value: 'Автомобильный', label: 'Автомобильный'},
    ];

    if (isLoading) {
        return <CapFerrySkeleton/>;
    }

    return (
        <div className={styles.ferryForm}>
            <div className={styles.ferryFormWrapper}>
                {currentImageUrl && (
                    <div className={styles.currentImage}>
                        <Image
                            src={currentImageUrl}
                            alt="Изображение парома"
                            className={styles.currentImagePreview}
                            quality={100}
                            width={500} height={500}
                            priority={true}
                        />
                    </div>
                )}
                <form onSubmit={handleSubmit(onSubmit)}>
                    <FormInput<TypeFerry>
                        id="name"
                        type="text"
                        name="name"
                        label="Название"
                        kind="none"
                        register={register}
                        rules={{required: "Введите название парома"}}
                        errors={errors}
                    />

                    <FormSelect<TypeFerry>
                        id="captain"
                        name="captain_id"
                        label="Выберите капитана"
                        options={captainOptions}
                        register={register}
                        rules={{}}
                        errors={errors}
                    />

                    <FormSelect<TypeFerry>
                        id="ferry_type"
                        name="ferry_type"
                        label="Выберите тип парома"
                        options={ferryTypeOptions}
                        register={register}
                        rules={{required: "Тип парома обязателен"}}
                        errors={errors}
                    />
                    {isVehicleType && (
                        <>
                            <FormInput<TypeFerry>
                                id="size"
                                type="number"
                                name="size"
                                label="Площадь места для ТС"
                                kind="none"
                                min={0}
                                register={register}
                                rules={{required: "Введите площадь места для ТС"}}
                                errors={errors}
                            />

                            <div className={styles.readOnlyField}>
                                <FormInput<TypeFerry>
                                    id="vehicle_capacity"
                                    type="number"
                                    name="vehicle_capacity"
                                    label="Количество мест для ТС"
                                    kind="none"
                                    readOnly={true}
                                    register={register}
                                    rules={{required: "Введите площадь места для ТС"}}
                                    errors={errors}
                                />
                            </div>
                        </>
                    )}

                    <FormInput<TypeFerry>
                        id="passenger_capacity"
                        type="number"
                        name="passenger_capacity"
                        label="Количество мест для пассажиров"
                        kind="none"
                        min={0}
                        register={register}
                        rules={{required: "Введите количество мест для пассажиров"}}
                        errors={errors}
                    />

                    <div className={styles.imageSection}>
                        <label htmlFor="image">Изображение</label>
                        <input type="file" {...register("image", {required: false})} />
                    </div>

                    <Button type="submit" kind="submit" content="Сохранить"/>
                </form>
            </div>
        </div>
    );
}
